﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Turtle8
{
    public partial class ZimunimCard : UserControl
    {
        IMofa mofa;
        DataTable dt = new DataTable();
        SqlDataAdapter da;

        public SqlDataAdapter SqlDataAdapter
        {
            get{  return da; }
            set{   da = value;}
        }


        public ZimunimCard(IMofa m)
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

            mofa = m;

            string selectStr = CompanyManager.getSqlStringFromFile(@"\SELECT\ZimunimCard.SELECT.sql");
            string updateStr = CompanyManager.getSqlStringFromFile(@"\UPDATE\ZimunimCard.UPDATE.sql");
            string deleteStr = "DELETE FROM [Table] WHERE (armyID=@armyID AND startDate=@startDate)";
            string insertStr = "INSERT INTO [Table] VALUES (@startDate,@armyID,@isDirectiveSent,@isApprovedArrival,@comments)";
            
            selectStr = selectStr.Replace("Table", mofa.TableName);
            updateStr = updateStr.Replace("Table", mofa.TableName);
            deleteStr = deleteStr.Replace("Table", mofa.TableName);
            insertStr = insertStr.Replace("Table", mofa.TableName);

            da = SqlManager.SqlDataAdapterFactory(selectStr);
            da.UpdateCommand = SqlManager.SqlCommandFactory(updateStr);
            da.DeleteCommand = SqlManager.SqlCommandFactory(deleteStr);
            da.InsertCommand = SqlManager.SqlCommandFactory(insertStr);

            ICollection<string> sqlParameterCollection = CompanyManager.parseSqlQueryParameters(updateStr);
            sqlParameterCollection.Distinct<string>();

            //adding parameters dynamically to the UPDATE SqlCommand
            foreach (string item in sqlParameterCollection)
            {
                string sItem = "@" + item;
                switch (item)
                {
                    case "armyID": 
                        da.UpdateCommand.Parameters.Add(CompanyManager.createSqlParameter(sItem, SqlDbType.NVarChar, DataRowVersion.Original, "armyID"));
                        da.DeleteCommand.Parameters.Add(CompanyManager.createSqlParameter(sItem, SqlDbType.NVarChar, DataRowVersion.Original, "armyID"));
                        da.InsertCommand.Parameters.Add(CompanyManager.createSqlParameter(sItem, SqlDbType.NVarChar, DataRowVersion.Original, "armyID"));
                        break;
                    case "comments":
                        da.UpdateCommand.Parameters.Add(CompanyManager.createSqlParameter("@comments", SqlDbType.NVarChar, DataRowVersion.Current, "comments"));
                        da.InsertCommand.Parameters.Add(CompanyManager.createSqlParameter("@comments", SqlDbType.NVarChar, DataRowVersion.Current, "comments"));
                        break;

                    case "startDate": 
                        DateTime dt1 = mofa.StartDate;
                        da.UpdateCommand.Parameters.Add(new SqlParameter("@startDate", SqlDbType.Date)).Value = dt1;
                        da.InsertCommand.Parameters.Add(new SqlParameter("@startDate", SqlDbType.Date)).Value = dt1;
                        da.DeleteCommand.Parameters.Add(new SqlParameter("@startDate", SqlDbType.Date)).Value = dt1;
                        da.SelectCommand.Parameters.Add(new SqlParameter("@startDate", SqlDbType.Date)).Value = dt1;
                        break;

                    default:
                        da.UpdateCommand.Parameters.Add(CompanyManager.createSqlParameter("@" + item, SqlDbType.Bit, DataRowVersion.Current, item));
                        da.InsertCommand.Parameters.Add(CompanyManager.createSqlParameter("@" + item, SqlDbType.Bit, DataRowVersion.Current, item));
                        break;

                }
            }

            refresh();
        }


        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            da.Update(dt);
            dt.AcceptChanges();
            refresh();

            labelSuccessfulUpdate.Visible = true;
            labelSuccessfulUpdate.Location = new Point(splitContainer.Panel1.Bounds.Width / 2, 16);
            timer1.Interval = 5 * 1000;
            timer1.Start();

            
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection rows = dataGridView.SelectedRows;
            int armyID_index = dataGridView.Columns["armyID"].Index;

            //update TahasukaAlal DB table.       
            mofa.deleteSoldierFromMofa(rows, armyID_index);
            if (mofa.GetType().Name.Equals("TahasukaCard"))
            {
                TahasukaCard tCard = (TahasukaCard)mofa;
                foreach (DataGridViewRow row in rows)
                    tCard.deleteAllSoldierRequests((string)row.Cells["armyID"].Value);              
            }

            //just after i make all other tables modifications i can really delete the rows from the current dataGridView
            DataGridViewSelectedRowCollection selected_row_col = dataGridView.SelectedRows;

            foreach (DataGridViewRow row in selected_row_col)
                dataGridView.Rows.Remove(row);

            try
            {
                da.Update(dt);
            }
            catch (Exception)
            {


            }
            
            refresh();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            IList<string> alreadyCalledList = new List<string>();

            //adds all soldiers armyID's currently in the table
            int armyID_index = dt.Columns.IndexOf("armyID");
            foreach (DataRow row in dt.Rows)
                alreadyCalledList.Add((string)row[armyID_index]);

            ZimunimList z_list = new ZimunimList(mofa, alreadyCalledList, ZimunimList.TableOption.NotCalledYet);
            dataGridView.Columns["comments"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            z_list.Text = "רשימת לוחמים פעילים אשר טרם זומנו";
            DialogResult result =  z_list.ShowDialog();

            dt.Clear();

            if (result==DialogResult.OK && mofa.ArmyIDList.Count>0)
            {
                da.InsertCommand.Parameters["@isDirectiveSent"].Value = false;
                da.InsertCommand.Parameters["@isApprovedArrival"].Value = false;
                da.InsertCommand.Parameters["@comments"].Value = String.Empty;

                mofa.addSoldiersToMofa();
            }
            
            refresh();
        }
        
        private void refresh() 
        {
            mofa.ArmyIDList.Clear();
            dt.Clear();
            da.Fill(dt);
            
            dataGridView.DataSource = dt;
            CompanyManager.setTableColumnHeadersHebrew(dataGridView.Columns);
            dataGridView.Refresh();

            dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dataGridView.Columns["comments"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridView.Columns["firstName"].ReadOnly = true;
            dataGridView.Columns["lastName"].ReadOnly = true;
            dataGridView.Columns["armyID"].ReadOnly = true;

            dataGridView.Columns["startDate"].Visible = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            labelSuccessfulUpdate.Visible = false;
        }

        public override string ToString()
        {
            return "מעקב זימונים";
        }
    }
}
